﻿Public Class Chat
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

        UpdateChatMessageList()
        'ScriptManager1.SetFocus(txtMessage.ClientID)
        ScriptManager.GetCurrent(Me.Page).SetFocus(txtMessage.ClientID)

    End Sub

    Private Sub UpdateChatMessageList()

        Dim cmMessages As List(Of ChatManager.ChatMessage) = Nothing
        Dim cmMessage As ChatManager.ChatMessage = Nothing
        Dim strMessages As List(Of String) = New List(Of String)

        Try

            cmMessages = ChatManager.RecieveMessage()

            If Not cmMessages Is Nothing AndAlso cmMessages.Count > 0 Then

                For Each cmMessage In cmMessages

                    strMessages.Add(cmMessage.MessageDate & " - " & cmMessage.User.Email & ": " & cmMessage.Message)

                Next

            Else

                strMessages.Add("No current Chats.")

            End If

            blChatMessageList.DataSource = strMessages
            blChatMessageList.DataBind()

        Catch ex As Exception

        End Try

    End Sub

    Protected Sub cmdSendButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdSendButton.Click

        Dim cmMessage As ChatManager.ChatMessage = Nothing
        Dim tuCurrentUser As Trebuchet.User = Nothing

        Try

            If Not String.IsNullOrEmpty(txtMessage.Text.Trim) Then

                tuCurrentUser = DBHelper.GetUserByID(HttpContext.Current.Session("User_id"))

                cmMessage = New ChatManager.ChatMessage(tuCurrentUser, txtMessage.Text.Trim, Now())
                ChatManager.SendMessage(cmMessage)
                txtMessage.Text = ""

            End If

            UpdateChatMessageList()
            UpdatePanel1.Update()

        Catch ex As Exception

        End Try

    End Sub

End Class